﻿using Treca.PushMessage.Business;
using Treca.PushMessage.Entity;
using Treca.Util;
using EFCore.Sharding;
using Microsoft.AspNetCore.Mvc;
using System.Data;
using Microsoft.AspNetCore.Http;
using Treca.Util.Helper;
using System;
using Newtonsoft.Json;
using System.IO;
using System.Linq;
using HtmlAgilityPack;
using Microsoft.AspNetCore.StaticFiles;
using System.Collections.Generic;
using Treca.Business.Base_SysManage;
using Treca.WebBase;
using Treca.WebUtil;
using static Treca.Entity.DataRule.EnumType;

namespace Treca.PushMessage.Controllers
{
    [Area("PushMessage")]
    [Route("PushMessage/{controller=Home}/{action=Index}/{id?}")]
    public class ms_messagetempleteController : BaseMvcController
    {
        #region DI
        BaseDataHelper listHelper;
        
          public ms_messagetempleteController(Ims_messagetempleteBusiness ms_messagetempleteBus)
        {
            //单表定义
            _ms_messagetempleteBus = ms_messagetempleteBus;
            listHelper=_ms_messagetempleteBus.GetBaseDataHelper();
        } 
        Ims_messagetempleteBusiness _ms_messagetempleteBus { get; } 
        

        #endregion

        #region 视图功能
        //列表
        public ActionResult Index()
        {
            ViewData["listHelper"] = listHelper;
            return View();
        } 

        public ActionResult GetIndex(string returnkey)
        {
            ViewData["returnkey"] = returnkey;
            ViewData["listHelper"] = listHelper;
            return View();
        }

        public ActionResult IndexMain(string key,string value,string guid,bool isview=false)
        {
            ViewData["key"] = key;
            ViewData["value"] = value;
            ViewData["guid"] = guid;
            ViewData["isview"] = isview;
            ViewData["listHelper"] = listHelper;
            var theData = new DataTable();
            if (!key.IsNullOrEmpty()&&!value.IsNullOrEmpty()) {
                List<SearchInfo> searchInfos = new List<SearchInfo>();
                SearchInfo searchInfo = new SearchInfo();
                searchInfo.FiledName = key;
                searchInfo.Value = value;
                searchInfo.Operate = FiledRuleOperate.等于;
                searchInfos.Add(searchInfo);
                theData = _ms_messagetempleteBus.GetDataList(new Pagination(),searchInfos);
            }
            ViewData.Model = theData;
            return View(theData);;
        }

        //弹窗选择
        public ActionResult PopForm()
        {
            return View();
        }
        //主从窗口
        public ActionResult MainForm()
        {
            ViewData["listHelper"] = listHelper;
            return View();
        }

        //复制单据
        public ActionResult CopyForm(string id,bool isview=false)
        {
            var theData = id.IsNullOrEmpty() ? new ms_messagetemplete() : _ms_messagetempleteBus.GetTheData(id);
            theData.Id="";
            ViewData["isview"] = isview;
            ViewData["listHelper"] = listHelper;
            return View("Form",theData);
        }
        //弹窗输入
        public ActionResult Form(string id,bool isview=false)
        {
            var theData = id.IsNullOrEmpty() ? new ms_messagetemplete() : _ms_messagetempleteBus.GetTheData(id);
            ViewData["isview"] = isview;
            ViewData["listHelper"] = listHelper;
            return View(theData);
        }
        //打印窗口
        //public ActionResult Print(string id)
        //{
        //    var theData = id.IsNullOrEmpty() ? new color() : _colorBus.GetTheData(id);

        //    return View(theData);
        //}
        //弹窗输入
        public ActionResult FormMain(string rownum,string guid,string key,string value)
        {
            ViewData["key"] = key;
            ViewData["value"] = value;
            ViewData["rownum"] = rownum;
            ViewData["guid"] = guid;
            ViewData["listHelper"] = listHelper;
            return View();
        }

        #endregion

        #region 获取数据


        public AjaxResult GetLinkData(string areaName, string entityName, string FiledName, string ValueName, ms_messagetemplete theData)
        {
            var data = _ms_messagetempleteBus.GetBaseDataHelper().GetLinkData<ms_messagetemplete>(areaName, entityName, FiledName, ValueName, theData);
            return AjaxHelper.Success(data);
        }

        /// <summary>
        /// 获取数据列表
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="condition">查询类型</param>
        /// <param name="keyword">关键字</param>
        /// <returns></returns>
        public ActionResult GetDataList(Pagination pagination,Dictionary<string, string> keyValues)
        {
            var dataList = _ms_messagetempleteBus.GetDataList(pagination,keyValues);

            return DataTable_Bootstrap(dataList, pagination);
        }

        /// <summary>
        /// 获取数据列表
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="condition">查询类型</param>
        /// <param name="keyword">关键字</param>
        /// <returns></returns>
        public ActionResult GetDataListBySearchInfo(Pagination pagination, List<SearchInfo> searchInfos)
        {
                var dataList = _ms_messagetempleteBus.GetDataList(pagination, searchInfos);

                return DataTable_Bootstrap(dataList, pagination);
        }

        /// <summary>
        /// 获取数据列表
        /// </summary>
        /// <param name="pagination">分页参数</param>
        /// <param name="ComplexQuerys">查询参数树</param>
        /// <returns></returns>
        public ActionResult GetDataListByComplexQuery(Pagination pagination, ComplexQuery ComplexQuerys)
        {
                var dataList = _ms_messagetempleteBus.GetDataListByComplexQuery(pagination, ComplexQuerys);
                return DataTable_Bootstrap(dataList, pagination);
        }

            /// <summary>
            /// 获取数据列表
            /// </summary>
            /// <param name="condition">查询类型</param>
            /// <param name="keyword">关键字</param>
            /// <returns></returns>
            public ActionResult GetDataTable(Pagination pagination,Dictionary<string, string> keyValues)
        {
            var dataList = _ms_messagetempleteBus.GetDataTable(pagination,keyValues);

            return DataTable_Bootstrap(dataList, pagination);
        }
        /// <summary>
        /// 后台通过获取数据列表
        /// </summary>
        /// <param name="key">查询参数</param> 
        /// <returns></returns>
        [IgnoreLogin]
        public ActionResult GetDataTableSql(string system, string Respondents, string ID_card, string Telephone, string Name, string Gate)
        {
            var dataList = _ms_messagetempleteBus.GetDataTableSql(system, Respondents, ID_card, Telephone, Name,  Gate);
            Pagination pagination = new Pagination();
            return DataTable_Bootstrap(dataList, pagination);
        }
        #endregion

        #region 提交数据

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="theData">保存的数据</param>
        public ActionResult SaveData(ms_messagetemplete theData)
        {
            AjaxResult s = new AjaxResult();
            if (theData.Id.IsNullOrEmpty())
            {
                theData.Id = IdHelper.GetId();
                s = _ms_messagetempleteBus.AddData(theData);
            }
            else
            {
                s = _ms_messagetempleteBus.UpdateData(theData);
            }
            return JsonContent(s.ToJson());
        }
        
        /// <summary>
        /// 复制保存
        /// </summary>
        /// <param name='theData'>保存的数据</param>
        public ActionResult CopySaveData(ms_messagetemplete theData)
        {
            AjaxResult s = new AjaxResult();           
            theData.Id = IdHelper.GetId();
            s = _ms_messagetempleteBus.AddData(theData);
            
            return JsonContent(s.ToJson());
        }


        /// <summary>
        /// 保存
        /// </summary>
        /// <param name='theData'>保存的数据</param>
        public ActionResult MainSaveData(ms_messagetemplete theData)
        {

           ///*
           // MainSaveData
           // 数据校验实现：
           // 1、字段必填
           // 2、业务逻辑校验，单据先后条件
           // 3、库存金额数量校验，剩余数量大于等于0

           // */
           // //有code例则生成
           // if (ContainProperty(theData, "Code"))
           // {
           //     if (theData.Code.IsNullOrEmpty())
           //     {
           //         theData.Code = GetDateNo();
           //     }
           // }
        
                var action = new Action(() =>
                {  
                    AjaxResult s = new AjaxResult();
                    if (theData.Id.IsNullOrEmpty()|| _ms_messagetempleteBus.GetTheData(theData.Id).IsNullOrEmpty())
                    {
                        theData.Id = IdHelper.GetId();
                        s = _ms_messagetempleteBus.AddData(theData);
                    }
                    else
                    {
                        s = _ms_messagetempleteBus.UpdateData(theData);
                    }
                    
                });
                var res =_ms_messagetempleteBus.RunTransaction(action);
                if (!res.Item1) return Error(res.Item2.Message);
                return Success();
            }
        //  /// <summary>
        //  /// 利用反射来判断对象是否包含某个属性
        //  /// </summary>
        //  /// <param name=instance>object</param>
        //  /// <param name=propertyName>需要判断的属性</param>
        //  /// <returns>是否包含</returns>
        //    public static bool ContainProperty(ms_messagetemplete theData, string propertyName)
        //    {
        //        if (_ms_messagetempleteBus != null && !string.IsNullOrEmpty(propertyName))
        //        {
        //            System.Reflection.PropertyInfo[] propertys = theData.GetType().GetProperties();
        //            System.Reflection.PropertyInfo _findedPropertyInfo = theData.GetType().GetProperty(propertyName);
        //            return (_findedPropertyInfo != null);
        //        }
        //        return false;
        //    }

        //    //生成订单编码+年月+流水号（例子，修改为根据规则生成物料编码、基础资料编码）
        //    //编码前缀及规则从codegenerate表中取得
        //    //编码的规则：前缀(不限长度)+yyyymm(6位)+流水码(不限长度)
        //    //编码长度 = 前缀+日期+流水码
        //    private string GetDateNo()
        //{
        //    string purchaseOrderNo;
        //    string date = DateTime.Now.ToString("yyyy" + "MM");
        //    string maxNo = _ms_messagetempleteBus.GetMaxNo("Code", ms_messagetemplete);//获取编号最大值（CGDD201906-002）
        //    DataTable list = _ms_messagetempleteBus.GetCodeSql(ms_messagetemplete);
        //    //映射单据字段名
        //    string MapDocFieldName = list.Rows[0]["MapDocFieldName"].ToString();
        //    //前缀
        //    string Prefix = list.Rows[0]["Prefix"].ToString();
        //    //后缀
        //    string Postfix = list.Rows[0]["Postfix"].ToString();
        //    //序号长度
        //    int SeriationLen = int.Parse(list.Rows[0]["SeriationLen"].ToString());
        //    //编码长度
        //    int CodeLength = int.Parse(list.Rows[0]["CodeLength"].ToString());
        //    string maxDate = maxNo.Substring(Prefix.Length, 6);//得到订单编号最大值的“年月”部分(201906)
        //    string maxDateNo = maxNo.Substring(CodeLength, SeriationLen);//得到编号最大值的序列部分，也就是“-”之后的三个数字（002）
        //    if (date == maxDate)//如果本月有数据
        //    {

        //            int.TryParse(maxDateNo, out int dd);//将订单编号的序列部分转换为 int 类型，以便进行“+1”运算
        //            int newDateNo = dd + 1;
        //            //编码的规则：前缀+yyyymm+流水码
        //            purchaseOrderNo = Prefix + date + " - " + newDateNo.ToString("0000000000".Substring(0, SeriationLen));

        //     }
        //    else
        //    {
        //            purchaseOrderNo = Prefix + date + " - " + "0000000001".Substring(10 - SeriationLen, SeriationLen);// “-”和 “001” 分开写会更清晰些

        //     }

        //    return purchaseOrderNo;
        //}
 
            /// <summary>
            /// 导入数据
            /// </summary>
            /// <param name="theData">保存的数据</param>
            public ActionResult SaveDatas(List<ms_messagetemplete> theData)
            {
            (bool, Exception) res = (true, new Exception(""));
            AjaxResult s = new AjaxResult();
            theData=listHelper.SelectListData<ms_messagetemplete>(theData);
      
            var action = new Action(() =>
            {
                foreach (ms_messagetemplete item in theData)
                {
                    if (item.Id.IsNullOrEmpty()||_ms_messagetempleteBus.GetTheData(item.Id).IsNullOrEmpty())
                    {
                        item.Id = IdHelper.GetId();

                        s = _ms_messagetempleteBus.AddData(item);
                    }
                    else
                    {
                        s = _ms_messagetempleteBus.UpdateData(item);
                    }
                }
            });
                res =_ms_messagetempleteBus.RunTransaction(action);
                if (!res.Item1) return Error(res.Item2.Message);
                return Success();
            }

            /// <summary>
            /// 删除数据
            /// </summary>
            /// <param name="theData">删除的数据</param>
        public ActionResult DeleteData(string ids)
        {
            var res = _ms_messagetempleteBus.DeleteData(ids.ToList<string>());

            return JsonContent(res.ToJson());
        }

        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="ids">审核</param>
        public ActionResult ApproveData(string ids)
        {
            var res = _ms_messagetempleteBus.ApproveData(ids.ToList<string>());

            return JsonContent(res.ToJson());
        }

        /// <summary>
        /// 反审核
        /// </summary>
        /// <param name="ids">反审核</param>
        public ActionResult ReverseData(string ids)
        {
            var res = _ms_messagetempleteBus.ReverseData(ids.ToList<string>());

            return JsonContent(res.ToJson());
        }


        /// <summary>
        /// 表单文字识别输入
        /// </summary>
        /// <param name="ids">表单文字识别输入</param>
        public ActionResult OCRData(string FileName)
        {
            FileName = GetPath() + "\\" + FileName;

            var res = _ms_messagetempleteBus.OCRData(FileName);

            return JsonContent(res.ToJson());

        }

        public string GetPath()
        {
            return Treca.Util.GlobalSwitch.WebRootPath.ToString();
        }

        IPrintService printService { get => AutofacHelper.GetScopeService<IPrintService>(); }


            public ActionResult PrintList(string condition = "", string keyword = "")
            {
                var dataList = _ms_messagetempleteBus.GetDataList(condition, keyword);
                string FileName = printService.CreatePrint(dataList,"ms_messagetemplete", false);
                return RedirectToAction("HtmlPrint", "t_printtemplate",new { area = "WebUtil",path = FileName.Base64Encode() });
            }

            public ActionResult Print(string Id)
            {
                var dataList = _ms_messagetempleteBus.GetDataList("Id",Id);
                List<DataTable> list = new List<DataTable>();
                
                string FileName = printService.CreatePrintData(dataList, list, "ms_messagetemplete", false);
                return RedirectToAction("HtmlPrint", "t_printtemplate",new { area = "WebUtil",path = FileName.Base64Encode() });
            }
            public ActionResult DownLoadFile(string FileName) {
            try
            {
                var stream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//推荐此方法
                string fileExt = Path.GetExtension(FileName);
                //获取文件的ContentType
                var provider = new FileExtensionContentTypeProvider();
                var memi = provider.Mappings[fileExt];
                return File(stream, memi, Path.GetFileName(FileName));
            }
            catch (Exception ex)
            {
                return NotFound();
            }
            }
            /// <summary>
            /// 获取数据列表
            /// </summary>
            /// <param name="condition">查询类型</param>
            /// <param name="keyword">关键字</param>
            /// <returns></returns>
            public ActionResult ExportExcel(string condition="", string keyword="")
        {
            var dataList = _ms_messagetempleteBus.GetDataList(condition,keyword);
            return CreateExcel(dataList);
        }


        public ActionResult ExportExcelBySearchInfo(List<SearchInfo> searchInfos,string idlist)
        {   
            var ids = idlist?.ToList<string>();
            if (ids.IsNullOrEmpty()||ids.Count == 0)
            {
                var dataList = _ms_messagetempleteBus.GetDataListIntersectExport(new Pagination(), searchInfos);
                return CreateExcel(dataList);
            }
            else {
                SearchInfo searchInfo = new SearchInfo();
                searchInfo.FiledName = "Id";
                searchInfo.Operate = FiledRuleOperate.被包含;
                searchInfo.Value = string.Join(',', ids);
                searchInfos.Add(searchInfo);
                var dataList = _ms_messagetempleteBus.GetDataListIntersectExport(new Pagination(), searchInfos);
                return CreateExcel(dataList);
            }
        }

        public ActionResult ExportExcelByComplexQuery(ComplexQuery ComplexQuerys,string idlist)
        {   
            if (ComplexQuerys.IsNullOrEmpty())
            {
                ComplexQuerys = new ComplexQuery();
            }
            var ids = idlist?.ToList<string>();
            if (ids.IsNullOrEmpty()||ids.Count == 0)
            {
                var dataList = _ms_messagetempleteBus.GetDataListIntersectExport(new Pagination(), ComplexQuerys);
                return CreateExcel(dataList);
            }
            else {
                 ComplexQuery _ComplexQuerys = new ComplexQuery();
                _ComplexQuerys.condition = "AND";
                ComplexQuery _ComplexQuerys_Rule = new ComplexQuery();
                _ComplexQuerys_Rule.field = "Id";
                _ComplexQuerys_Rule.@operator="in";
                _ComplexQuerys_Rule.value = string.Join(',', ids);
                _ComplexQuerys.rules.Add(ComplexQuerys);
                _ComplexQuerys.rules.Add(_ComplexQuerys_Rule);
                var dataList = _ms_messagetempleteBus.GetDataListIntersectExport(new Pagination(),_ComplexQuerys);
                return CreateExcel(dataList);
            }
        }
        

        public AjaxResult ComplexQueryFilters()
        {
            return listHelper.ComplexQueryFilters<ms_messagetemplete>("PushMessage", "ms_messagetemplete");
        }



        /// <summary>
        /// 导出到Excel并下载
        /// </summary>
        public ActionResult CreateExcel(DataTable theData)
        {
               string FileName =ExcelHelper.ChangeExcelDown(theData,"ms_messagetemplete");
               return DownLoadFile(FileName);
        }
        
        /// <summary>
        /// 获取数据列表
        /// </summary>
        /// <param name="condition">查询类型</param>
        /// <param name="keyword">关键字</param>
        /// <returns></returns>
        public ActionResult CreateExportExcel()
        {
            var dataList = _ms_messagetempleteBus.GetDataList();
            return CreateExportExcelC(dataList);
        }
        /// <summary>
        /// 导入格式
        /// </summary>
        public ActionResult CreateExportExcelC(DataTable theData)
        {
            string FileName = ExcelHelper.ChangeExcelDown(theData, "ms_messagetemplete",true);
            try
            {
                var stream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//推荐此方法
                string fileExt = Path.GetExtension(FileName);
                //获取文件的ContentType
                var provider = new FileExtensionContentTypeProvider();
                var memi = provider.Mappings[fileExt];
                return File(stream, memi, Path.GetFileName(FileName));
            }
            catch (Exception ex)
            {
                return NotFound();
            }
        }
        
        /// <summary>
        /// 导入excel数据到DB
        /// </summary>
        /// <returns>导入excel数据到DB</returns>
        [HttpPost]
        public ActionResult ExportData(ms_messagetemplete theData)
        {
            var file1 = Request.Form.Files["file"]; 
            byte[] fileBytes = new byte[file1.Length];
            file1.OpenReadStream().Read(fileBytes, 0, int.Parse(file1.Length.ToString()));
            string excelData = System.Text.Encoding.UTF8.GetString(fileBytes);
            return SaveDatas(ExcelHelper.ExcelToDataTable<ms_messagetemplete>(file1.OpenReadStream()));
        }
        #endregion
     }
}